import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_douban/config/app_config.dart';
import 'package:flutter_douban/config/event_bus_util.dart';
import 'package:flutter_douban/main_page/me/view/setting_view.dart';
import 'package:flutter_douban/tool_views/app_dialog.dart';
import 'package:flutter_douban/tool_views/back_nav_btn.dart';
import 'package:flutter_douban/tool_views/nav_title_page.dart';
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'feed_back_page.dart';

class SettingPage extends StatefulWidget {
  const SettingPage({Key? key}) : super(key: key);

  @override
  _SettingPageState createState() => _SettingPageState();
}

class _SettingPageState extends State<SettingPage> {
  List _list = [
    '视频自动播放设置',
    '联系我们',
    '帮助中心',
    '给我们打分',
    '用户协议',
    '隐私条款',
    '系统设置',
    '清理缓存',
    '退出登录'
  ];
  List unitArr = [];
  String _valueStr = '';

  /// 获取缓存
  Future<double> loadApplicationCache() async {
    /// 获取文件夹
    Directory directory = await getApplicationDocumentsDirectory();

    /// 获取缓存大小
    double value = await getTotalSizeOfFilesInDir(directory);
    return value;
  }

  /// 循环计算文件的大小（递归）
  Future<double> getTotalSizeOfFilesInDir(final FileSystemEntity file) async {
    if (file is File) {
      int length = await file.length();
      return double.parse(length.toString());
    }
    if (file is Directory) {
      final List<FileSystemEntity> children = file.listSync();
      double total = 0;
      if (children != null)
        for (final FileSystemEntity child in children)
          total += await getTotalSizeOfFilesInDir(child);
      return total;
    }
    return 0;
  }

  /// 缓存大小格式转换
  String formatSize(double value) {
    if (null == value) {
      return '0';
    }
    unitArr..add('B')..add('K')..add('M')..add('G');
    int index = 0;
    while (value > 1024) {
      index++;
      value = value / 1024;
    }
    String size = value.toStringAsFixed(2);
    return size + unitArr[index];
  }

  /// 获取缓存
  Future<void> _getData() async {
    double value = await loadApplicationCache();
    String str = formatSize(value);
    setState(() {
      _valueStr = str;
    });
    print('获取app缓存: ' + str);
  }

  /// 删除缓存
  void clearApplicationCache() async {
    Directory directory = await getApplicationDocumentsDirectory();
    //删除缓存目录
    await deleteDirectory(directory);
  }

  /// 递归方式删除目录
  Future<Null> deleteDirectory(FileSystemEntity file) async {
    if (file is Directory) {
      final List<FileSystemEntity> children = file.listSync();
      for (final FileSystemEntity child in children) {
        await deleteDirectory(child);
      }
    }
    await file.delete();
  }

  /// 退出登录
  Future<void> logout() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.remove(AppConfig.numberId);
    AppDialog.showText(context, title: '操作成功~');
    EventBusUtil.fire(LoginEvent(LoginEvent.logOut));
    Navigator.pop(context);
  }

  /// 点击事件
  void didSelect(String itemStr){
    if (itemStr == '联系我们') {
      Navigator.of(context).push(MaterialPageRoute(builder: (_) {
        return FeedBackPage();
      }));
      return;
    }

    if (itemStr == '退出登录') {
      AppDialog.showIosAlert(context, content: '确认退出登录吗?', onCancel: () {},
          onConfirm: () {
            logout();
          });
      return;
    }

    if (itemStr == '清理缓存') {
      deleteDirectory;
      print('删除缓存');
      return;
    }

  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: NavTitlePage(
          titleStr: '设置',
        ),
        leading: BackNavBtn(),
      ),
      body: Container(
        color: Colors.white,
        child: ListView.builder(
            itemCount: _list.length,
            // shrinkWrap: true, //增加
            itemBuilder: (BuildContext context, int index) {
              return SettingView(
                string: _list[index],
                valueStr: _valueStr,
                onConfirm: didSelect,
              );
            }),
      ),
    );
  }
}
